package com.ustarlink.live;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.VideoView;

import java.io.FileNotFoundException;

public class MainActivity extends Activity {
    private ChannelsAdapter mAdapter;
    private ListView channelList;
    private VideoView videoView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        channelList = (ListView)findViewById(R.id.lv_second_menu);
        videoView = (VideoView)findViewById(R.id.vv_live_container);
        /**节目列表点击监听事件***/
        channelList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = mAdapter.getItem(position).getChannelUrl();
                videoView.setVideoURI(Uri.parse(url));
                videoView.start();
            }
        });
        /**如果网络可用开始下载**/
        if(isNetworkAvailable()){
            Log.i("uStarLink Live", "starting download Task");
            EPGDownloadTask download = new EPGDownloadTask();
            download.execute();
        }else{
            mAdapter = new ChannelsAdapter(getApplicationContext(), -1, ChannelXmlPullParser.getChannelFromFile(MainActivity.this));
            channelList.setAdapter(mAdapter);
        }
    }

    private class EPGDownloadTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            //Download the file
            try {
                Downloader.DownloadFromURL("http://www.cfm880.com/wp-content/uploads/2015/12/tvs_epg.xml", openFileOutput("tvs_epg.xml", Context.MODE_PRIVATE));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            // 添加到ListView中
            mAdapter = new ChannelsAdapter(MainActivity.this, -1, ChannelXmlPullParser.getChannelFromFile(MainActivity.this));
            channelList.setAdapter(mAdapter);
            Log.i("uStarLink Live Channel", "adapter size = " + mAdapter.getCount());
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }



}
